package com.fangcang.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MapUtil {

	/**
	 * 将Object 转换成Map
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object> obj2Map(Object obj) {
        Map<String,Object> map=new HashMap<String, Object>();
        BeanInfo beanInfo;
		try {
			beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) { 
				String key = property.getName();
				if (key.compareToIgnoreCase("class") == 0) {   
					continue;  
				}  
				Method getter = property.getReadMethod();  
				Object value = getter!=null ? getter.invoke(obj) : null;  
				map.put(key, value); 
			}
		} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new RuntimeException("Object convert to Map fail：", e);
		}
        return map;
    }
}
